<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\SmsMsg;
use App\Model\SystemMsg;
use App\Model\UserBonusCount;
use App\Model\UserDetail;
use App\Model\UserInterPushInfo;
use App\Model\UserInviteOneYuan;
use App\Model\UserSalesmanBonusCount;
use App\Model\UserSalesmanInviteOneYuan;
use App\Model\UserUp;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Swagger\Annotations as SWG;

/**
 * Class AuthController
 * @package App\Http\Controllers\Front
 */
class AuthController extends Controller
{

    //region 密码登录
    /**
     *
     * @SWG\Post(
     *     path="/front/login",
     *     summary="密码登录",
     *     tags={"登录注册"},
     *     description="密码登录",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(name="phone", in="formData", required=true, type="string", description="手机号"),
     *     @SWG\Parameter(name="password", in="formData", required=true, type="string", description="密码"),
     *     @SWG\Response(
     *         response=200,
     *         description="返回授权凭证",
     *         @SWG\Schema(
     *             type="json",
     *             @SWG\Property(property="token", type="string", description="凭证"),
     *             @SWG\Property(property="expire", type="integer", description="过期时间")
     *         )
     *     )
     * )
     */
    public function login(Request $request, User $u)
    {
        $rules = [
            'phone' => ['required', 'regex:/^1[345789][0-9]{9}$/'],
            'password' => 'required|string|min:6|max:20'
        ];

        $message = [
            'required' => ':attribute不能为空',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'phone.regex' => '手机号不正确',
        ];

        $attribute = [
            'phone' => '手机号',
            'password' => '密码'
        ];

        $this->validate($request, $rules, $message, $attribute);//验证

        //登录验证字段

        $user = $u->where('phone', '=', request('phone'))->whereIn('type', [3, 4])->first();
        if ($user == null or !password_verify(request('password'), $user->password)) {
            return $this->fail('用户名或密码错误');
        }
        if ($user->is_enabled == 1){
            return $this->fail('你的账号已被禁用');
        }
        //登录成功记录数据
        $this->loginLog($user);
        return $this->send(['token' => Auth::guard('api')->fromUser($user), 'expire' => '2592000']);
    }
    //endregion

    //region 短信登录
    /**
     *
     * @SWG\Post(
     *     path="/front/login/phone",
     *     summary="短信登录",
     *     tags={"登录注册"},
     *     description="短信登录",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(name="phone", in="formData", required=true, type="string", description="手机号"),
     *     @SWG\Parameter(name="code", in="formData", required=true, type="string", description="短信验证码"),
     *     @SWG\Response(
     *         response=200,
     *         description="返回授权凭证",
     *         @SWG\Schema(
     *             type="json",
     *             @SWG\Property(property="token", type="string", description="凭证" )
     *         )
     *     )
     * )
     */
    public function phoneLogin(Request $request, SmsMsg $msg)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^1[345789][0-9]{9}$/'],
            'code' => 'required'
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空'
        ]);


        $msg->validate(request('phone'), request('code'));

        $user = $user = User::where('phone', $request->input('phone'))->whereIn('type', [3, 4])->first();
        if ($user) {
            if (!in_array($user->type, [3, 4])) {
                return $this->fail('用户类型错误', 403);
            }
            $token = Auth::guard('api')->fromUser($user);
            $this->loginLog($user);
            return $this->send(['token' => $token]);
        }
        return $this->fail('用户不存在，请注册！');
    }

    //endregion
    //region 注册
    /**
     *
     * @SWG\Post(
     *     path="/front/register",
     *     summary="注册",
     *     tags={"登录注册"},
     *     description="注册",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(name="phone_number", in="formData", required=true, type="string", description="手机号"),
     *     @SWG\Parameter(name="code", in="formData", required=true, type="string", description="短信验证码"),
     *     @SWG\Parameter(name="password", in="formData", required=true, type="string", description="密码"),
     *     @SWG\Parameter(name="open_id", in="formData", required=true, type="string", description="微信openid"),
     *     @SWG\Response(
     *         response=200,
     *         description="返回授权凭证",
     *         @SWG\Schema(
     *             type="json",
     *             @SWG\Property(property="token", type="string", description="凭证"),
     *             @SWG\Property(property="expire", type="integer", description="过期时间"),
     *             @SWG\Property(property="user_id", type="integer", description="用户id"),
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @param User $user
     * @param UserDetail $userDetail
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */

    public function register(Request $request, User $user, UserDetail $userDetail, SmsMsg $msg)
    {
        $this->validate($request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
                'unique:users,phone'
            ],
//            'password' => 'required|string|min:6|max:20',
            'open_id' => 'required',
            'code' => 'required'
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'phone.unique' => '手机号被注册了',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'code.required' => '验证码不能为空',
            'open_id.required' => 'open_id不能为空'
        ]);
        $msg->validate($request->input('phone'), request('code')); // 验证电话+短信
        $phone    = $request->input('phone');
        $password = $request->input('password');
        $user_id  = $request->input("user_id"); // todo 邀请用户id
        $open_id = $request->input('open_id'); // TODO open_id 是user_id
        $user = $user->where("id", "=", $open_id)->first();
        // todo 查找出业务员
        $salesman = User::where('phone', $phone)->where('type', 3)->first();
        if ($salesman) {
            // 业务员进行注册
            $user_detail = $user->detail;
            $user_detail->user_id = $salesman->id;
            $user_detail->save();
            $user->delete();
            $token = Auth::guard('api')->fromUser($salesman);
            $this->init($salesman);
            return $this->send(['token' => $token, 'expire' => '2592000', 'user_id' => $user->id]);
        }
        // todo 会员
        $userPhone = User::where(['phone' => $phone, 'type' => 4])->first();
        if ($userPhone) {
            return $this->fail('用户已存在！');
        }

        if (isset($user->phone) && $user->phone !="") {
            return $this->fail('该微信账号已被绑定，请更换账号登录微信号后注册');
        }
        if (!$user) {
            return $this->fail('用户不存在！');
        }
        $user->phone = $phone;
        if ($password){
            $user->password = bcrypt($password);
        }
        $user->save();
        $this->init($user, $user_id);
        $token = Auth::guard('api')->fromUser($user);
        $this->loginLog($user);
        // 注册成功！
        return $this->send(['token' => $token, 'expire' => '2592000', 'user_id' => $user->id]);
    }

    //endregion

    public function logout()
    {
        Auth::guard('api')->logout();
        return $this->success('退出成功');
    }

    /**
     * 刚注册初始化用户数据
     * @param  User $user
     * @param $user_grade_id
     */
    private function init($user, $user_grade_id)
    {
       /*
       if (CardsPictureIntroductions::where('user_id', $user->id)->first()) {
            return;
        }

        $data = [
            'user_id' => $user->id,
            'title' => '自我介绍',
            'content' => ' ',
            'picture_path' => ' '
        ];
        $pictureIntroductions1 = new CardsPictureIntroductions;
        $data['type'] = 1;
        $pictureIntroductions1->create($data);

        $pictureIntroductions2 = new CardsPictureIntroductions;
        $data['type'] = 2;
        $data['title'] = '公司介绍';
        $pictureIntroductions2->create($data);
       */
        // 活动

        // 查找是否有人推荐
        $grade_user = User::where("id", $user_grade_id)->first();
        if ($grade_user){
            // 关系的建立
            $user->pid = $grade_user->id;
            $user->salesman_id = $grade_user->type == 3 ? $grade_user->id : $grade_user->salesman_id;
            $user->operator_id = $grade_user->operator_id;
            $user->place_partner_id = $grade_user->place_partner_id;
            $user->enterprise_user_id = $grade_user->enterprise_user_id;
            $user->save();
            // user_up 添加
            $grade_user_up =  UserUp::whereUserId($user_grade_id)->first();
            $user_up = new UserUp();
            $user_up->user_id = $user->id;
            $user_up->user_up_list = $grade_user_up->user_id.','.$grade_user_up->user_up_list;
            $user_up->save();
            // 判断推荐用户达到增加互推次数没有
            $regexp = $grade_user_up->id.','.$grade_user_up->user_up_list.'$';
            $num =  UserInterPushInfo::interPushNum ($regexp);
            $gradeUserInterPushInfo = $grade_user->interPushInfo;
            $redis = Redis::connection();
            $redis->select (0);

            $grade_num =  $num - $gradeUserInterPushInfo->num; // 查看推荐用户达到增加互推次数没有
            if ($grade_num){
                // 添加redis 推荐用户
                if ($redis->sismember (date('Ymd')."_" .$gradeUserInterPushInfo->province_id.'_city', $grade_num) ==0){
                    if ($gradeUserInterPushInfo->province_id != 0){
                        $redis->sadd (date('Ymd')."_0_city", $gradeUserInterPushInfo->id);
                    }
                    $redis->sadd (date('Ymd')."_" .$gradeUserInterPushInfo->province_id.'_city', $gradeUserInterPushInfo->id);
                    $redis->incrby("user_id".$gradeUserInterPushInfo->id, $grade_num); //增加次数
                }
            }
            // todo 互推 新用户
            $user_inter_push_info = new UserInterPushInfo();
            $user_inter_push_info->user_id = $user->id;
            $user_inter_push_info->save();
            // 写入互推redis

            $name1 = date('Ymd') . '_0_city';
            $redis->sadd ($name1, $user->interPushInfo->id);
//            \Log::info ($user_inter_push_info);
//            \Log::info ($user->interPushInfo->id);
            // 加入次数
            $redis->set("user_id_".$user->interPushInfo->id,2);

            // todo 活动佣金
            $this->activity($grade_user, $user->id,$user->detail->wechat_name,$user->phone,1);

        }else{
            // todo 互推 新用户
            $user_inter_push_info = new UserInterPushInfo();
            $user_inter_push_info->user_id = $user->id;
            $user_inter_push_info->save();
            // 写入互推redis
            $redis = Redis::connection();
            $redis->select (0);
            $name1 = date('Ymd') . '_0_city';
            $redis->sadd ($name1, $user->interPushInfo->id);
            // 加入次数
            $redis->set("user_id_".$user->interPushInfo->id,2);
            //todo
            $user_up = new UserUp();
            $user_up->user_id = $user->id;
            $user_up->user_up_list = 0;
            $user_up->save();

        }
    }

    /**
     * @param  User $user
     * @param $poster
     */
    public function  activity($user, $relation_user_id,  $name,$phone,  $poster)
    {
        // 修改活动
        try{
            \DB::beginTransaction();
            if ($user->type == 4){
                $user_invite_one_yuan = new  UserInviteOneYuan();
                $user_invite_one_yuan->money = 1;
                $user_invite_one_yuan->title = "活动奖励金";
                $user_invite_one_yuan->content = "邀请会员".$name."电话号码:".$phone;
                $user_invite_one_yuan->user_id = $user->id;
                $user_invite_one_yuan->relation_user_id = $relation_user_id;
                $user_invite_one_yuan->save();
                // 记录营销奖励金总表
                $user_bonus_count  = new UserBonusCount();
                $user_bonus_count->type = 2;
                $user_bonus_count->income_type = 1;
                $user_bonus_count->user_id = $user->id;
                $user_bonus_count->money = 1;
                $user_bonus_count->relation_id = $user_invite_one_yuan->id;
                $user_bonus_count->relation_user_id = $relation_user_id;
                $user_bonus_count->describe = "邀请会员".$name."电话号码:".$phone;
                $user_bonus_count->save();
                // 系统消息
                SystemMsg::add ($user->id,4,"活动奖励金","邀请会员".$name."电话号码:".$phone,1);

            }else{
                $user_salesman_invite_one_yuan = new UserSalesmanInviteOneYuan();
                $user_salesman_invite_one_yuan->money = 1;
                $user_salesman_invite_one_yuan->title = "活动奖励金";
                $user_salesman_invite_one_yuan->content = "邀请会员".$name."电话号码:".$phone;
                $user_salesman_invite_one_yuan->user_id = $user->id;
                $user_salesman_invite_one_yuan->relation_user_id = $relation_user_id;
                $user_salesman_invite_one_yuan->save();
                // 记录营销奖励金总表
                $user_salesman_bonus_count = new UserSalesmanBonusCount();
                $user_salesman_bonus_count->type = 2;
                $user_salesman_bonus_count->income_type = 1;
                $user_salesman_bonus_count->user_id = $user->id;
                $user_salesman_bonus_count->money = 1;
                $user_salesman_bonus_count->relation_user_id = $relation_user_id;
                $user_salesman_bonus_count->relation_id = $user_salesman_invite_one_yuan->id;
                $user_salesman_bonus_count->describe = "邀请会员".$name."电话号码:".$phone;
                $user_salesman_bonus_count->save();
                SystemMsg::add ($user->id,4,"活动奖励金","邀请会员".$name."电话号码:".$phone,1);
            }
            $user->increment("currentCommission"); // 增加营销奖励金
            $user->increment("rewards_all"); // 增加营销奖励金
            \DB::commit ();
        }catch (\Exception $exception){
            \DB::rollBack();
            \Log::error ($exception);
        }
    }
    private function loginLog(User $user)
    {
        $user->logged_ip = request()->getClientIp();
        $user->logged_at = date('Y-m-d H:i:s', time());
        $user->save();
    }

    public function refresh()
    {
        $token = Auth::guard('api')->refresh();
        return $this->send(['token' => $token, 'expire'=>'2592000']);
    }

    /**
     *
     * @SWG\Post(
     *     path="/front/account/reset",
     *     summary="重置密码",
     *     tags={"账户相关"},
     *     description="重置密码",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="phone", in="formData", required=true, type="string", description="手机号"),
     *     @SWG\Parameter(name="new_password", in="formData", required=true, type="string", description="新密码"),
     *     @SWG\Response(
     *         response=200,
     *         description="操作成功"
     *     )
     * )
     */
    public function reset(Request $request, User $user)
    {
        $this->validate($request, [
            'phone' => [
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'new_password' => 'required'
        ], [
            'phone_number.regex' => '手机号格式不正确',
            'new_password' => '密码是必填的'
        ]);

        $msg = new SmsMsg();
        $msg->validate($request->input('phone'), $request->input('code'));
        $user = $user->where(['phone' => $request->input('phone')])->first();
        $user->password = bcrypt($request->input('new_password'));
        $user->save();
        return $this->success();
    }

    /**
     * 手机是否存在
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function phoneExist(Request $request)
    {
        $phone = $request->input("phone");
        $user = User::where("phone", $phone)->whereIn ("type",[3,4])->first();
        if ($user){
            return $this->renderJson(['is_exist' => true]);
        }
        return $this->renderJson(['is_exist' => false]);
    }


    /**
     * 邀请会员注册
     * @param Request $request
     * @param User $user
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function appInvitationRegister(Request $request,User $user ,SmsMsg $msg)
    {
        $this->validate($request,[
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
        ],[
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
        ]);
        $phone = $request->input("phone");
        $code = $request->input("code");
        $pid  = $request->input("pid");
        $msg->validate ($phone, $code);

        if ($user->where("phone", "=", $phone)->whereIn("type",[3,4])->first ()){
            return $this->fail("该用户已经存在");
        }
        $user->phone = $phone;
        try{
            \DB::beginTransaction ();
            if ($pid && $parent = User::whereId ($pid)->first()){
                $user->pid = $parent->id;
                $user->salesman_id = $parent->type == 3 ? $parent->id : $parent->salesman_id;
                $user->operator_id = $parent->operator_id;
                $user->place_partner_id = $parent->place_partner_id;
                $user->enterprise_user_id = $parent->enterprise_user_id;
                $user->save();

                // pid 用户获取邀请营销奖励金一元
                if ($parent->type == 3){
                    $relation_id =  $parent->salesmanInviteOneYuan()->insertGetId ([
                        'title' => '一元拉新记录',
                        'user_id' => $parent->id,
                        'content' => '通过app邀请会员'.$user->phone."注册",
                        'money' => 1,
                        'relation_user_id' => $user->id,
                        'created_at' => Carbon::now()
                    ]);

                    $salesmanBonusCount = new UserSalesmanBonusCount();
                    $salesmanBonusCount->type = 2;
                    $salesmanBonusCount->income_type= 1;
                    $salesmanBonusCount->money = 1;
                    $salesmanBonusCount->relation_id = $relation_id;
                    $salesmanBonusCount->user_id = $parent->id;
                    $salesmanBonusCount->save();
                    // 增加营销奖金
                    $parent->increment("salesman_current_commission",1);

                }else{
                    $relation_id = $parent->inviteOneYuan()->insertGetId([
                        'title' => '一元拉新记录',
                        'user_id' => $parent->id,
                        'content' => '通过app邀请会员'.$user->phone."注册",
                        'money' => 1,
                        'relation_user_id' => $user->id,
                        'created_at' => Carbon::now()
                    ]);
                    $user_bonus_count = new UserBonusCount();
                    $user_bonus_count->type = 2;
                    $user_bonus_count->income_type= 1;
                    $user_bonus_count->money = 1;
                    $user_bonus_count->relation_id = $relation_id;
                    $user_bonus_count->user_id = $parent->id;
                    $user_bonus_count->save();
                    $parent->increment("current_commission",1);
                }
            }else{
                $user->save();
            }
            $user->detail()->save (new UserDetail());
            \DB::commit ();
        }catch (\Exception $exception){
         \Log::error ($exception);
         \DB::rollBack();
         return $this->error();
        }
      return $this->success();
    }

}
